#include<stdio.h>
#include"voice_interface.h"
#include"socket_interface.h"
#include"smoke_interface.h"
#include"receive_interface.h"
#include"msg_queue.h"
#include"control.h"
#include<pthread.h>
#include<wiringPi.h>
#include"global.h"



int main(int argc, char** argv)
{

    pthread_t thread_id;
    struct control* control_phead = NULL;// 使用工厂模式创建多个线程,先创建一个控制链表(监听链表)头
    struct control* pointer = NULL;
    ctrl_info_t* ctrl_info = NULL;
    int node_num = 0;
    ctrl_info = (ctrl_info_t*)malloc(sizeof(ctrl_info_t));
    ctrl_info->ctrl_phead = NULL;
    ctrl_info->mqd = -1;

    wiringPiSetup();

    ctrl_info->mqd = msg_queue_create();
    if (ctrl_info->mqd < 0)
    {
        printf("msg queue create failed\n");
        return -1;
    }

    ctrl_info->ctrl_phead = add_voice_to_ctrl_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_tcpsocket_to_ctrl_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_smoke_to_ctrl_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_receive_to_ctrl_list(ctrl_info->ctrl_phead);

    pointer = ctrl_info->ctrl_phead; // 复制一个指针指向头结点
    printf("control list ok\n");
    while (pointer != NULL)
    {

        if (pointer->init() == 0)//遍历初始化控制链表的节点
        {
            printf("init %s success\n", pointer->control_name);

        }
        else
        {
            printf("init %s failed\n", pointer->control_name);
            return -1;
        }
        pointer = pointer->next;
        // printf("initing %s\n", pointer->control_name);
        node_num++;
    }

    pthread_t* tid = (pthread_t*)malloc(sizeof(pthread_t) * node_num); // 为每个线程分配内存

    pointer = ctrl_info->ctrl_phead;
    // 遍历控制链表，为每个节点创建一个监听线程get()
    for (int i = 0; i < node_num; i++)
    {
        if (pointer->get != NULL)
            pthread_create(&tid[i], NULL, pointer->get, (void*)ctrl_info);//注意为什么不直接传&mqd 因为需要control这个结构体不仅仅只是队列mqd
        pointer = pointer->next;
    }
    // 等待所有线程结束 正常情况下监听线程会一直执行
    for (int i = 0; i < node_num; i++)
    {
        pthread_join(tid[i], NULL);
    }
    // 释放控制链表
    for (int i = 0; i < node_num; i++)
    {
        if (pointer->final != NULL)
        {
            pointer->final();
        }
        pointer = pointer->next;
    }
    // 释放消息队列 ctrl_info tid
    msg_queue_final(ctrl_info->mqd);
    if (ctrl_info != NULL)
        free(ctrl_info);
    if (tid != NULL)
        free(tid);
    return 0;
}


//sudo -E ./smarthome
//执行前先删除原来的队列
//sudo rm /dev/mqueue/mq_queue